Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

题目大意:给定一个链表,删除重复元素

题目难度:Easy

/**
 * Created by gzdaijie on 16/6/4
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode p = head.next;
        ListNode h = head;

        while (p != null) {
            if (p.val != h.val) h = h.next = p;
            p = p.next;
        }
        h.next = null;
        return head;
    }
}
gzdaijie            updated 2016-06-04 15:42:40

results matching ""

    No results matching ""